#include <QtAlgorithms>

#include "properties_item.h"

CPropertiesItem::CPropertiesItem(const QVector<QVariant>& pData, CPropertiesItem* pParent) :
	mData(pData),
	mParent(pParent)
{
}

CPropertiesItem::~CPropertiesItem()
{
	qDeleteAll(mChildren);
}

CPropertiesItem* CPropertiesItem::child(int pNum)
{
	return mChildren.value(pNum);
}

void CPropertiesItem::setChild(int pNum, CPropertiesItem* pItem)
{
	mChildren.replace(pNum, pItem);
}

CPropertiesItem* CPropertiesItem::parent()
{
	return mParent;
}

int CPropertiesItem::childCount() const
{
	return mChildren.count();
}

bool CPropertiesItem::insertChildren(int pPos, int pCnt, int pColumns)
{
	if (pPos < 0 || pPos > mChildren.size())
	{
		return false;
	}

	for (int lRow = 0; lRow < pCnt; ++lRow)
	{
		QVector<QVariant> lData(pColumns);
		CPropertiesItem* lItem = new CPropertiesItem(lData, this);
		mChildren.insert(pPos, lItem);
	}

	return true;
}

bool CPropertiesItem::removeChildren(int pPos, int pCnt)
{
	if (pPos < 0 || pPos + pCnt > mChildren.size())
	{
		return false;
	}

	for (int lRow = 0; lRow < pCnt; ++lRow)
	{
		delete mChildren.takeAt(pPos);
	}

	return true;
}

int CPropertiesItem::childNumber() const
{
	if (mParent)
	{
		return mParent->mChildren.indexOf(const_cast<CPropertiesItem*>(this));
	}
	
	return 0;
}

int CPropertiesItem::columnCount() const
{
	return mData.count();
}

QVariant CPropertiesItem::data(int pColumn) const
{
	return mData.value(pColumn);
}

bool CPropertiesItem::setData(int pColumn, const QVariant& pValue)
{
	if (pColumn < 0 || pColumn >= mData.size())
	{
		return false;
	}

	mData[pColumn] = pValue;
	return true;
}

